<?php
declare (strict_types = 1);

namespace app\admin\controller\v1;
use Throwable;
use app\common\Backend;
use app\common\model\Combo;
use app\common\model\Navigation;
use app\common\model\Product as ModelProduct;
use app\common\model\PublicStatus;
use general\Tree;
use general\Random;
use Qiniu\Auth;
use think\Request;

class Product extends Backend
{

    /**
     * @var Product
     */
    protected $tree = null;

    protected $model = null;

    protected $quickSearchField = ['title'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new ModelProduct();
        $this->tree = Tree::instance();

    }

     /**
     * 数据源
     * @throws Throwable
     */
    public function index(): void
    {
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model->where($where)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => '',
        ]);
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
          
            if (!$data) {
                $this->error(('Parameter %s can not be empty'));
            }
            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $parent_id = get_nav_parent($data['nav_id']);
            if(count($parent_id) == 0){ //返回的导航栏id
                $data['nav_one_id'] = $data['nav_id'];
            }
            if(count($parent_id) == 1){ 
                $data['nav_one_id'] = $parent_id[0];
                $data['nav_two_id'] = $data['nav_id'];
            }
            if(count($parent_id) == 2){ //返回的导航栏id
                $data['nav_one_id'] = $parent_id[0];
                $data['nav_two_id'] = $parent_id[1];
                $data['nav_three_id'] = $data['nav_id'];
            }
            $product_ids = 'KM'.Random::build('numeric',18);
            $data['product_ids'] = $product_ids;
            if(array_key_exists('search_key',$data)){
                if(!str_contains($data['search_key'],$data['product_ids'])){
                    $data['search_key'] = $data['product_ids'].','.$data['search_key'];
                }
            }else{
                $data['search_key'] = $data['product_ids'];
            }
    
            if(!array_key_exists('content',$data)){
                $data['banner_path'] = json_encode($data['banner_path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            }
            if(intval($data['is_choose']) == PublicStatus::PUBLIC_STATUS_ONE){
                if(array_key_exists('domains',$data)){
                    $combo_id_arr = [];
                    foreach($data['domains'] as $key=>$value){
                        $combo_id_arr[] = "".$value['key'];
                    }
                    $data['combo_id'] = json_encode($combo_id_arr, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                    $data['combo_json'] = json_encode($data['domains'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                }
            }else{
                if(array_key_exists('combo_id',$data)){
                    $combo_arr = [];
                    foreach($data['combo_id'] as $key=>$value){
                        $combo = Combo::field('id,title')->find($value);
                        $combo_arr[$key]['key'] = $combo['id'];
                        $combo_arr[$key]['value'] = $combo['title'];
                    }
                    $data['combo_id'] = json_encode($data['combo_id'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                    $data['combo_json'] = json_encode($combo_arr, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                }
            }
            // $data['project_config'] =  json_encode($data['project_config'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);      
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(('Added successfully'));
            } else {
                $this->error(('No rows were added'));
            }
        }
        $this->error(('Parameter error'));
    }



     /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(('Record not found'));
        }
        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(('You have no permission'));
        }
        if ($this->request->isPost()) {
            $data = $this->request->post();
         
            $parent_id = get_nav_parent($data['nav_id']);
            if(count($parent_id) == 0){ //返回的导航栏id
                $data['nav_one_id'] = $data['nav_id'];
            }
            if(count($parent_id) == 1){ 
                $data['nav_one_id'] = $parent_id[0];
                $data['nav_two_id'] = $data['nav_id'];
            }
            if(count($parent_id) == 2){ //返回的导航栏id
                $data['nav_one_id'] = $parent_id[0];
                $data['nav_two_id'] = $parent_id[1];
                $data['nav_three_id'] = $data['nav_id'];
            }
            if(!str_contains($data['search_key'],$data['product_ids'])){
                $data['search_key'] = $data['product_ids'].','.$data['search_key'];
            }
            if(!array_key_exists('content',$data)){
                $data['banner_path'] = json_encode($data['banner_path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            }
            if(intval($data['is_choose']) == PublicStatus::PUBLIC_STATUS_ONE){
                if(array_key_exists('domains',$data)){
                    $combo_id_arr = [];
                    foreach($data['domains'] as $key=>$value){
                        $combo_id_arr[] = "".$value['key'];
                    }
                    $data['combo_id'] = json_encode($combo_id_arr, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                    $data['combo_json'] = json_encode($data['domains'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                }
            }else{
                if(array_key_exists('combo_id',$data)){
                    $combo_arr = [];
                    foreach($data['combo_id'] as $key=>$value){
                        $combo = Combo::field('id,title')->find($value);
                        $combo_arr[$key]['key'] = $combo['id'];
                        $combo_arr[$key]['value'] = $combo['title'];
                    }
                    $data['combo_id'] = json_encode($data['combo_id'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                    $data['combo_json'] = json_encode($combo_arr, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                }
            }
            // $data['banner_path'] = json_encode($data['banner_path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);     
           // $data['project_config'] =  json_encode($data['project_config'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);   
            
            if (!$data) {
                $this->error(('Parameter %s can not be empty'));
            }
            $data   = $this->excludeFields($data);

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                    
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(('Update successful'));
            } else {
                $this->error(('No rows updated'));
            }
        }
        if(isJson($row['banner_path']) && !empty($row['banner_path'])){
            $row['banner_path'] = json_decode($row['banner_path'],true);
        }

        if(isJson($row['combo_id']) && !empty($row['combo_id'])){
            $row['combo_id'] = json_decode($row['combo_id'],true);
        }

        if(isJson($row['combo_json']) && !empty($row['combo_json'])){
            $row['domains'] = json_decode($row['combo_json'],true);
        }
        // if(isJson($row['project_config']) && !empty($row['project_config'])){
        //     $row['project_config'] = json_decode($row['project_config'],true);
        // }
        $this->success('', [
            'row' => $row
        ]);
    }


    protected function getSelectList(): array
    {

        $res = Navigation::where(['pid'=>0,'status'=>1])->select()->toArray();
        $isSelect = [];
        foreach($res as $key=>$argv){
            $isSelect[$argv['id']] = $argv['title'];
        }
        return $isSelect;
    }



    


}